<template>
  <div class="app-container">
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="800px" v-dialogDrag append-to-body>
      <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="故障编号" prop="faultTypeCode">
              <el-input v-model="formData.faultTypeCode" placeholder="请输入故障编号" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="故障名称" prop="faultTypeName">
              <el-input v-model="formData.faultTypeName" placeholder="请输入故障名称" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="上级故障类型" prop="parentId">
              <el-select v-model="formData.parentId" placeholder="请选择上级故障类型" style="width: 100%" filterable>
                <el-option label="无" :value="0" />
                <el-option v-for="item in faultTypeList" :key="item.id" :label="item.faultTypeName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="formData.status">
                <el-radio v-for="dict in getDictDatas(DICT_TYPE.COMMON_STATUS)" :key="dict.value"  :label="parseInt(dict.value)">
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as FaultTypeApi from '@/api/devices/faulttype';
import {getDictDatas, DICT_TYPE} from '@/utils/dict'

export default {
  name: "FaultTypeForm",
  components: {
  },
  data() {
    return {
      // 弹出层标题
      dialogTitle: "",
      // 是否显示弹出层
      dialogVisible: false,
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 故障类型列表（用于上级选择）
      faultTypeList: [],
      // 表单参数
      formData: {
        id: undefined,
        faultTypeCode: undefined,
        faultTypeName: undefined,
        parentId: 0, // 默认值设为0，表示无上级
        status: '1', // 默认启用状态
      },
      // 表单校验
      formRules: {
        faultTypeCode: [
          { required: true, message: '请输入故障编号', trigger: 'blur' }
        ],
        faultTypeName: [
          { required: true, message: '请输入故障名称', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      },
    };
  },
  methods: {
    /** 打开弹窗 */
    async open(id) {
      this.dialogVisible = true;
      this.reset();
      // 修改时，设置数据
      if (id) {
        this.formLoading = true;
        try {
          const res = await FaultTypeApi.getFaultType(id);
          this.formData = res.data;
          // 确保parentId有值，没有则设为0
          if (this.formData.parentId === undefined || this.formData.parentId === null) {
            this.formData.parentId = 0;
          }
          this.dialogTitle = "修改故障类型";
        } finally {
          this.formLoading = false;
        }
      } else {
        this.dialogTitle = "新增故障类型";
        this.formData.parentId = 0; // 新增时默认无上级
      }
      // 获取故障类型列表用于上级选择
      await this.getFaultTypeList();
    },

    /** 获取故障类型列表 */
    async getFaultTypeList() {
      try {
        const res = await FaultTypeApi.getFaultTypePage({ pageSize: 100, parentId: 0 });
        // 过滤掉当前正在编辑的故障类型，避免选择自己作为上级
        this.faultTypeList = res.data.list.filter(item => item.id !== this.formData.id);
      } catch (error) {
        this.$modal.msgError('获取故障类型列表失败');
      }
    },

    /** 提交按钮 */
    async submitForm() {
      // 校验主表
      await this.$refs["formRef"].validate();
      this.formLoading = true;
      try {
        const data = this.formData;
        // 修改的提交
        if (data.id) {
          await FaultTypeApi.updateFaultType(data);
          this.$modal.msgSuccess("修改成功");
          this.dialogVisible = false;
          this.$emit('success');
          return;
        }
        // 添加的提交
        await FaultTypeApi.createFaultType(data);
        this.$modal.msgSuccess("新增成功");
        this.dialogVisible = false;
        this.$emit('success');
      } finally {
        this.formLoading = false;
      }
    },

    /** 表单重置 */
    reset() {
      this.formData = {
        id: undefined,
        faultTypeCode: undefined,
        faultTypeName: undefined,
        parentId: 0, // 默认值设为0，表示无上级
        status: 1, // 默认启用状态
      };
      this.resetForm("formRef");
    }
  }
};
</script>
